<template>
  <div class="home">
    <el-header class="header">
      <div class="left-input">
        <div class="electric-fence">
          <el-input placeholder="请输入电子围栏名称" v-model="name" @keyup.enter.native="searchEnter" @input="getFenceForm" clearable></el-input>
        </div>
        <div class="select-unit">
          <el-select v-model="organizationId" placeholder="所属单位" @input="getFenceForm" clearable>
            <el-option v-for="item in orgOpt" :key="item.value" :label="item.label" :value="item.value" >
            </el-option>
          </el-select>
        </div>
      </div>
      <div header-botton2>
        <el-button type="primary" @click="getFenceForm">搜索</el-button>
        <el-button type="success" @click="getFenceForm">重置</el-button>
        <el-button type="info"  @click="addMethod">新增</el-button>
      </div>
    </el-header>
    <el-main class="fence-table">
      <el-table :data="tableData" height="320" border style="width: 100%;">
      <el-table-column prop="id" label="序号"></el-table-column>
      <el-table-column prop="name" label="围栏名称"></el-table-column>
      <el-table-column prop="groupVO.name" label="单位"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
        <el-button type="text" @click="editMethod(scope.$index, scope.row)" class="edit-button">
          <div class="bottom">
          <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
              <img class="edit" src="../assets/img/编辑.png">
          </el-tooltip>
          </div>
        </el-button>
        <el-popover placement="top" width="160" :ref="`popover-${scope.$index}`">
          <p>确定删除？</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="closeDeleteWindow(scope)">取消</el-button>
            <el-button type="primary" size="mini" @click="deleteMethod(scope.row.id)">确定</el-button>
          </div>
          <el-button type="text" slot="reference" class="delete-button">
            <div class="bottom">
              <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
              <img class="delete" src="../assets/img/删除.png">
              </el-tooltip>
            </div>
          </el-button>
        </el-popover>
        </template>
      </el-table-column>
      </el-table>
      <!-- 新增弹窗 -->
      <div class="map">
        <el-dialog :visible.sync="addFenceVisible">
          <el-form :model="addFence" inline>
            <el-form-item class="electric-fence" label="围栏" >
              <el-input v-model="addFence.name" placeholder="输入电子围栏名称" clearable></el-input>
            </el-form-item>
            <el-form-item class="select-unit" label="单位" >
              <el-select v-model="addFence.organizationId" placeholder="选择所属单位" clearable>
                <el-option v-for="item in orgOpt" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        <div id="addFenceMap" class="allmap"></div>
        <div class="searchStyle">
            <el-input v-model="searchAddress" placeholder="输入地址" @input="searchArea"/>
        </div>
        <ul class="drawing-panel">
          <li class="bmap-btn bmap-marker" @click="draw('drag')" :style="{ 'background-position-y': actNav === 'drag' ? '-52px' : '0px'}"></li>
          <li class="bmap-btn bmap-rectangle" @click="draw('rectangle')" :style="{ 'background-position-y': actNav === 'rectangle' ? '-52px' : '0px' }"></li>
          <li class="bmap-btn bmap-polygon" @click="draw('polygon')" :style="{'background-position-y': actNav === 'polygon' ? '-52px' : '0px'}"></li>
          <li class="bmap-btn bmap-circle" @click="draw('circle')" :style="{'background-position-y': actNav === 'circle' ? '-52px' : '0px'}"></li>
        </ul>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitAddFence">提交新增</el-button>
            <el-button size="mini" @click="addFenceVisible=false">取消</el-button>
        </div>
        </el-dialog>
      </div>
      <!-- 编辑弹窗 -->
      <div class="map">
        <el-dialog :visible.sync="editFenceVisible">
          <el-form :model="editFence" inline>
            <el-form-item class="electric-fence" label="围栏" >
              <el-input v-model="editFence.name" placeholder="输入电子围栏名称" clearable></el-input>
            </el-form-item>
            <el-form-item class="select-unit" label="单位" >
              <el-select v-model="editFence.groupVO.id" placeholder="选择所属单位" :popper-append-to-body="false" clearable>
                <el-option v-for="item in orgOpt" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        <!-- 地图容器 -->
        <div id="editFenceMap" class="allmap"></div>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" size="mini" @click="submitChangeFence">提交修改</el-button>
            <el-button size="mini" @click="editFenceVisible=false">取消</el-button>
        </div>
        </el-dialog>
      </div>
    </el-main>
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-sizes="pageList"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper, sizes"
        :total="total"
        :data="tableData">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getFence, getTree, addFence, changeFence, deleteFence } from '../api/fence/index'
// 引入异步引入地图的方法
import { loadBaiDuDrawMap } from '../api/map/bmpgl_lib'
export default {
  data () {
    return {
      // 搜索地址绑定数据
      searchAddress: '',
      // 所属单位下拉框
      orgOpt: [],
      // 所属单位
      organizationId: '',
      input: '',
      currentPage: 1,
      total: null,
      pageSize: 5,
      pageList: [5, 10, 20, 30],
      tableData: null,
      name: '',
      id: '',
      // 增加弹窗可视化
      addFenceVisible: false,
      // 编辑弹窗可视化
      editFenceVisible: false,
      // 地图
      map: null,
      actNav: '',
      // 新增数据数据
      addFence: {
        name: '',
        organizationId: null,
        pointList: '',
        radius: 0,
        type: 0
      },
      // 编辑数据
      editFence: {
        name: '',
        groupVO: {
          id: ''
        },
        pointList: '',
        radius: 0,
        type: 0
      }
    }
  },
  mounted () {
    this.getFenceForm()
    this.getOrgOpt()
  },
  methods: {
    handleSizeChange (size) {
      console.log(`每页 ${size} 条`)
      this.pageSize = size
      this.currentPage = 1
      this.getFenceForm()
    },
    handleCurrentChange (cur) {
      console.log(`当前页: ${cur}`)
      this.currentPage = cur
      this.getFenceForm()
    },
    // 关闭弹出框
    closeDeleteWindow (scope) {
      scope._self.$refs[`popover-${scope.$index}`].doClose()
    },
    // 删除电子围栏
    deleteMethod (row) {
      console.log(row)
      this.id = row
      console.log(this.id)
      deleteFence(this.id).then((res) => {
        console.log(res)
        console.log('删除电子围栏')
        if (res.data.message === '成功') {
          this.$message({
            type: 'success',
            message: '成功删除电子围栏'
          })
          this.getFenceForm()
        } else {
          this.$message({
            type: 'error',
            message: '删除电子围栏失败'
          })
        }
      })
    },
    // 触发回车事件
    searchEnter (e) {
      var keyCode = window.Event ? e.keyCode : e.which
      if (keyCode === 13) {
        this.getFenceForm()
      }
    },
    getFenceForm () {
      getFence({
        currentPage: this.currentPage,
        id: this.id,
        name: this.name,
        organizationId: this.organizationId
      })
        .then((res) => {
          console.log('调用电子围栏数据')
          console.log(res)
          this.tableData = res.data.data.records
          this.total = res.data.data.total
        }).catch((error) => {
          console.log(error)
        })
    },
    // 组织树转数组
    ChangeOrgArr (tree) {
      const parentArr = []
      const chidrenArr = []
      tree && tree.forEach(item => {
        parentArr.push({
          label: item.name,
          value: item.id
        })
        if (item.children) {
          chidrenArr.push(...this.ChangeOrgArr(item.children))
        }
      })
      // 合并子数组与父数组
      this.orgOpt = parentArr.concat(chidrenArr)
      return this.orgOpt
    },
    // 获取所属单位存入下拉框
    getOrgOpt () {
      getTree().then((res) => {
        console.log(res)
        this.ChangeOrgArr(res.data.data)
      })
    },
    // 新增弹窗按钮
    addMethod () {
      this.addFenceVisible = true
      this.initMap()
    },
    // 编辑弹窗按钮
    editMethod (index, row) {
      this.editFenceVisible = true
      this.editFence = Object.assign({}, row)
      console.log('编辑弹窗操作数据')
      console.log(this.editFence)
      this.initMap()
    },
    // 地图
    initMap () {
      // 初始化地图
      loadBaiDuDrawMap().then((BMapGL) => {
        // 创建地图实例
        let point = null
        // eslint-disable-next-line no-unused-vars
        let container = ''
        // 判断为新增地图或是编辑地图
        if (this.addFenceVisible === true) {
          container = 'addFenceMap'
          point = new BMapGL.Point(114.031761, 22.542826)
        } else {
          // 编辑弹窗
          container = 'editFenceMap'
          const b = JSON.parse(this.editFence.pointList)
          console.log('获取坐标集合：')
          console.log(b)
          // 判断为圆还是多边形。确定中心
          if (this.editFence.type === 0) {
            // 创建点坐标
            point = new BMapGL.Point(b.lng, b.lat)
            // 根据坐标、半径创建圆
            this.circle = new BMapGL.Circle(point, this.editFence.radius,
              {
                strokeColor: '#5E87DB',
                fillColor: '#5E87DB',
                strokeWeight: 2,
                strokeOpacity: 1,
                fillOpacity: 0.2
              })
          } else {
            const c = []
            point = new BMapGL.Point(b[0].lng, b[0].lat)
            // 将坐标点循环取存
            for (let i = 0; i < b.length; i++) {
              const point1 = new BMapGL.Point(b[i].lng, b[i].lat)
              c.push(point1)
            }
            this.polygon = new BMapGL.Polygon(c, {
              strokeColor: '#5E87DB',
              fillColor: '#5E87DB',
              strokeWeight: 2,
              strokeOpacity: 1,
              fillOpacity: 0.2
            })
            console.log('多边形点坐标集合：')
            console.log(c)
          }
        }
        const map = new BMapGL.Map(container)
        // 添加比例尺控件
        map.addControl(
          new BMapGL.ScaleControl({
            // eslint-disable-next-line no-undef
            anchor: BMAP_ANCHOR_BOTTOM_LEFT,
            offset: new BMapGL.Size(10, 10)
          })
        )
        // 添加缩放控件
        map.addControl(
          new BMapGL.ZoomControl({
            // eslint-disable-next-line no-undef
            anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
            offset: new BMapGL.Size(10, 10)
          })
        )
        // 添加3D控件
        map.addControl(
          new BMapGL.MapTypeControl({
            mapTypes: [
              // eslint-disable-next-line no-undef
              BMAP_NORMAL_MAP,
              // eslint-disable-next-line no-undef
              BMAP_HYBRID_MAP
            ]
          })
        )
        // 个性化地图
        map.setMapStyleV2({
          styleId: '94e12a0a8e1da0b38877c171dd7f1311'
        })
        // 保存地图
        this.map = map
        // 创建点坐标 axios => res 获取的初始化定位坐标
        // 初始化地图，设置中心点坐标和地图级别
        map.centerAndZoom(point, 19)
        // 开启鼠标滚轮缩放
        // 判断为编辑弹窗时开启绘画功能
        if (this.editFenceVisible === true) {
          if (this.editFence.type === 0) {
            // 增加圆
            map.addOverlay(this.circle)
            this.circle.enableEditing()
          } else {
            map.addOverlay(this.polygon)
            this.polygon.enableEditing()
          }
        }
        map.enableScrollWheelZoom(true)
        map.setHeading(0)
      })
    },
    draw (type) {
      this.actNav = type
      const styleOptions = {
        strokeColor: '#5E87DB', // 边线颜色
        fillColor: '#5E87DB', // 填充颜色。当参数为空时，圆形没有填充颜色
        strokeWeight: 2, // 边线宽度，以像素为单位
        strokeOpacity: 1, // 边线透明度，取值范围0-1
        fillOpacity: 0.2 // 填充透明度，取值范围0-1
      }
      // eslint-disable-next-line no-unused-vars
      const labelOptions = {
        borderRadius: '2px',
        background: '#FFFBCC',
        border: '1px solid #E1E1E1',
        color: '#703A04',
        fontSize: '12px',
        letterSpacing: '0',
        padding: '5px'
      }
      // 实例化鼠标绘制工具
      // eslint-disable-next-line no-undef
      const drawingManager = new BMapGLLib.DrawingManager(this.map, {
        enableCalculate: false, // 绘制是否进行测距测面
        enableSorption: true, // 是否开启边界吸附功能
        sorptiondistance: 20, // 边界吸附距离
        rectangleOptions: styleOptions, // 矩形的样式
        polygonOptions: styleOptions,
        labelOptions
      })
      if (drawingManager.isOpen && drawingManager.getDrawingMode() === type) {
        drawingManager.close()
      } else {
        drawingManager.setDrawingMode(type)
        drawingManager.open()
      }
      // 绘制完成的事件
      drawingManager.addEventListener('overlaycomplete', this.overlaycomplete)
    },
    // 监听绘制图案
    overlaycomplete (e) {
      if (e.drawingMode === 'circle') {
        // 绘制圆
        this.radius = e.overlay.getRadius()
        this.points = e.overlay.getCenter()
        this.type = 0
      } else {
        // 否则为多边形
        this.radius = 0
        // 存储绘画的点坐标
        this.points = []
        for (let i = 0; i < e.overlay.getPath().length; i++) {
          this.points.push({ lng: e.overlay.getPath()[i].lng, lat: e.overlay.getPath()[i].lat })
        }
        this.type = 1
        console.log('绘制多边形，坐标点为：')
        console.log(this.points)
      }
      this.drag()
    },
    // 拖拽时的函数
    drag () {
      this.actNav = 'drag'
    },
    // 点击检索关键字
    searchArea () {
      // 清除地图上所有覆盖物
      this.map.clearOverlays()
      // 实现关键字检索
      // eslint-disable-next-line no-undef
      const local = new BMapGL.LocalSearch(this.map, {
        renderOptions: { map: this.map }
      })
      local.search(this.searchAddress)
    },
    // 新增电子围栏方法
    submitAddFence () {
      addFence({
        name: this.addFence.name,
        organizationId: this.addFence.organizationId.toString(),
        pointList: this.points,
        radius: this.radius,
        type: this.type
      }).then((res) => {
        console.log('成功新建电子围栏')
        console.log(res)
        if (res.data.message === '成功') {
          this.$message({
            type: 'success',
            message: '成功新建电子围栏'
          })
          // 清空新增弹窗
          this.points = []
          this.radius = 0
          this.type = 0
          this.searchAddress = ''
          this.addFence.name = ''
          this.addFence.organizationId = null
          this.addFenceVisible = false
          this.getFenceForm()
        } else {
          this.$message({
            type: 'error',
            message: res.data.message
          })
        }
      })
    },
    // 提交电子围栏修改
    submitChangeFence () {
      if (this.editFence.type === 0) {
        console.log('编辑的图形为圆')
        this.editFence.radius = this.circle.getRadius()
        this.editFence.pointList = this.circle.grtCenter()
        this.circle.disableEditing()
      } else {
        this.editFence.pointList = this.polygon.getPath()
        this.polygon.disableEditing()
      }
      changeFence(this.editFence).then((res) => {
        console.log(res)
        console.log('成功修改电子围栏')
        if (res.data.message === '成功') {
          this.$message({
            type: 'success',
            message: '成功修改电子围栏！'
          })
          this.polygon = null
          this.circle = null
          this.editFenceVisible = false
          this.getFenceForm()
        } else {
          this.$message({
            type: 'error',
            message: '修改电子围栏失败'
          })
        }
      }).catch(err => {
        console.log(err)
        console.log('调用失败')
      })
    }
  }
}
</script>

<style scoped>
.electric-fence >>> .el-input__inner {
  border-radius: 0;
  border: 1px solid #238cd6;
  background-color: #061d3c;
  height: 28px;
  margin-right: 10px;
  width: 160px;
  font-size: 4px;
}
/* 下拉选择框 */
.select-unit >>> .el-input__inner {
  border-radius: 0;
  border: 1px solid #238cd6;
  background-color: #061d3c;
  height: 28px;
  width: 160px;
  margin-right: 10px;
  font-size: 4px;
  color: white;
}
.header {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
  width: 100%;
}
.left-input {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: space-evenly;
  width: 350px;
}
.header-botton2 {
  width: 300px;
  margin-left: 20px;
}
/* 编辑删除样式 */
.el-button {
  width: 70px;
  height: 28px;
  padding: 0;
  font-size: 6px;
  border-radius: 0;
}
.edit {
  background-size: 100% 100%;
  width: 18px;
  height: 18px;
}
.delete {
  background-size: 100% 100%;
  width: 18px;
  height: 18px;
}
/* 编辑弹框 */
.edit-button.el-button {
  width: 18px;
}
.bottom {
  clear: both;
  text-align: center;
}
/* 表格 */
.fence-table {
  margin-left: 20px;
  margin-right: 20px;
}
.el-main {
  padding: 0;
}
/* 分页 */
.block {
  margin-top: 10px;
}
/* 弹框面板 */
.map >>> .el-dialog__body {
  padding-bottom: 10px;
  width: 591px;
  height: 490px;
  background-size: 100% 100%!important;
  background-image: url(../assets/img/整体效果.png);
}
.map >>> .el-dialog__footer {
  margin-right: 60px;
  position: relative;
  top: -55px;
}
.map >>> .el-form-item__label {
  color: #238cd6;
  font-size: 13px;
}
/* 隐藏滚动轴 */
.map::-webkit-scrollbar{
  display: none;
}
.map >>> .el-dialog {
  background: transparent;
}
/* 百度地图 */
.bm-view {
  width: 100%;
  height: 500px;
}
.map >>> .el-form-item {
    margin-bottom: 4px;
}
.searchStyle >>> .el-input__inner {
  width: 100px;
  height: 28px;
  margin-left: 20px;
  top: -380px;
  position: relative;
  z-index: 999;
  border-radius: 0;
}
.allmap {
  width: 591px;
  height: 400px;
  position: relative;
  z-index: 1;
}
.change-map-type {
  position: absolute;
  right: 50px;
  bottom: 10px;
  z-index: 2;
}
ul li {
  list-style: none;
}
.info {
  z-index: 999;
  width: auto;
  min-width: 22rem;
  padding: 0.75rem 1.25rem;
  margin-left: 1.25rem;
  position: fixed;
  top: 1rem;
  background-color: #fff;
  border-radius: 0.25rem;
  font-size: 14px;
  color: #666;
  box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
}
.drawing-panel {
  bottom: 430px;
  z-index: 999;
  position: relative;
  float: right;
  right: 90px;
  border-radius: 0.25rem;
  height: 47px;
}
.bmap-btn {
  border-right: 1px solid #d2d2d2;
  float: left;
  width: 64px;
  height: 100%;
  background-image: url(http://api.map.baidu.com/library/DrawingManager/1.4/src/bg_drawing_tool.png);
  cursor: pointer;
}
.drawing-panel .bmap-marker {
  background-position: 0 0;
}
.drawing-panel .bmap-rectangle {
  background-position: -325px 0;
}
.drawing-panel .bmap-polygon {
  background-position: -260px 0;
}
.drawing-panel .bmap-circle {
  background-position: -130px 0;
}
</style>
